<?php
/**
 * starcor 新版 全国运营CDN注入
 * @author jing.chen
 */
include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_class/ftp/ftp.class.php';
include_once dirname(dirname(dirname(__FILE__))).'/nn_db.class.php';
class c2_task_model_v2 extends nn_public_model
{
    /**
     * 组装片源信息
     * @param unknown $arr_info 片源基本信息
     * @param string $arr_info_ex 扩展数据
     * @return string
     */
    private function make_media_xml($arr_info,$str_Action,$arr_info_ex=null)
    {
        $str_xml   ='<Object ElementType="Movie" ContentID="'.$arr_info['nns_import_id'].'" Action="'.$str_Action.'" code="'.$arr_info['nns_import_id'].'">';
        $str_xml  .=	'<Property Name="Type">'.$arr_info['nns_filetype'].'</Property>';
        $str_xml  .=	'<Property Name="FileURL">'.$arr_info['nns_url'].'</Property>';
        $str_xml  .=	'<Property Name="CPContentID">'.$arr_info['nns_cp_id'].'</Property>';
        $str_xml  .=	'<Property Name="SourceDRMType"></Property>';
        $str_xml  .=	'<Property Name="DestDRMType"></Property>';
        $str_xml  .=	'<Property Name="AudioType"></Property>';
        $str_xml  .=	'<Property Name="ScreenFormat"></Property>';
        $str_xml  .=	'<Property Name="ClosedCaptioning"></Property>';
        $str_xml  .=	'<Property Name="Tags">'.$arr_info['nns_tag'].'</Property>';
        $str_xml  .=	'<Property Name="Duration">'.$arr_info['nns_file_time_len'].'</Property>';
        $str_xml  .=	'<Property Name="FileSize">'.$arr_info['nns_file_size'].'</Property>';
        $str_xml  .=	'<Property Name="BitRateType">'.$arr_info['nns_kbps'].'</Property>';
        $str_xml  .=	'<Property Name="VideoType">'.$arr_info_ex['file_coding'].'</Property>';
        $str_xml  .=	'<Property Name="AudioEncodingType"></Property>';
        $str_xml  .=	'<Property Name="Resolution">'.$arr_info['nns_file_resolution'].'</Property>';
        $str_xml  .=	'<Property Name="MediaMode">'.$arr_info['nns_mode'].'</Property>';
        $str_xml  .=	'<Property Name="SystemLayer"></Property>';
        $str_xml  .=	'<Property Name="ServiceType">'.$arr_info['nns_media_service'].'</Property>';
        $str_xml  .=	'<Property Name="Domain">'.$arr_info['nns_domain'].'</Property>';
        $str_xml  .=	'<Property Name="Hotdegree"></Property>';
        $str_xml.='</Object>';
        return $str_xml;
    }
    /**
     * 组装分集信息
     * @param unknown $arr_info 分集基本信息
     * @param string $arr_info_ex 扩展数据
     * @return string
     */
    private function make_index_xml($arr_info,$str_Action,$arr_info_ex=null)
    {
        $str_xml   ='<Object ElementType="Program" ContentID="'.$arr_info['nns_import_id'].'" Action="'.$str_Action.'" code="'.$arr_info['nns_import_id'].'">';
        $str_xml  .=	'<Property Name="Name">'.$arr_info['nns_name'].'</Property>';
        $str_xml  .=	'<Property Name="CPContentID">'.$arr_info['nns_cp_id'].'</Property>';
        $str_xml  .=	'<Property Name="OrderNumber"></Property>';
        $str_xml  .=	'<Property Name="OriginalName">'.$arr_info['nns_name'].'</Property>';
        $str_xml  .=	'<Property Name="Sequence">'.$arr_info['nns_index'].'</Property>';
        $str_xml  .=	'<Property Name="SortName"></Property>';
        $str_xml  .=	'<Property Name="SearchName"></Property>';
        $str_xml  .=	'<Property Name="OriginalCountry"></Property>';
        $str_xml  .=	'<Property Name="ActorDisplay">'.$arr_info['nns_actor'].'</Property>';
        $str_xml  .=	'<Property Name="WriterDisplay">'.$arr_info['nns_director'].'</Property>';
        $str_xml  .=	'<Property Name="Language"></Property>';
        $str_xml  .=	'<Property Name="OrgAirDate">'.$arr_info['nns_kbps'].'</Property>';
        $str_xml  .=	'<Property Name="ReleaseYear">'.$arr_info_ex['year'].'</Property>';
        $str_xml  .=	'<Property Name="LicensingWindowStart"></Property>';
        $str_xml  .=	'<Property Name="LicensingWindowEnd"></Property>';
        $str_xml  .=	'<Property Name="DisplayAsNew"></Property>';
        $str_xml  .=	'<Property Name="DisplayAsLastChance"></Property>';
        $str_xml  .=	'<Property Name="Macrovision"></Property>';
        $str_xml  .=	'<Property Name="Description">'.$arr_info['nns_summary'].'</Property>';
        $str_xml  .=	'<Property Name="PriceTaxIn"></Property>';
        $str_xml  .=	'<Property Name="Status"></Property>';
        $str_xml  .=	'<Property Name="SourceType"></Property>';
        $str_xml  .=	'<Property Name="SeriesFlag"></Property>';
        $str_xml  .=	'<Property Name="ContentProvider">'.$arr_info['nns_cp_id'].'</Property>';
        $str_xml  .=	'<Property Name="KeyWords">'.$arr_info_ex['sreach_key'].'</Property>';
        $str_xml  .=	'<Property Name="Tags"></Property>';
        $str_xml  .=	'<Property Name="ViewPoint">'.$arr_info['nns_watch_focus'].'</Property>';
        $str_xml  .=	'<Property Name="StarLevel"></Property>';
        $str_xml  .=	'<Property Name="Rating"></Property>';
        $str_xml  .=	'<Property Name="Awards"></Property>';
        $str_xml  .=	'<Property Name="Duration">'.$arr_info['nns_time_len'].'</Property>';
        $str_xml  .=	'<Property Name="Reserve1"></Property>';
        $str_xml  .=	'<Property Name="Reserve2"></Property>';
        $str_xml  .=	'<Property Name="Reserve3"></Property>';
        $str_xml  .=	'<Property Name="Reserve4"></Property>';
        $str_xml  .=	'<Property Name="Reserve5"></Property>';
        $str_xml  .='</Object>';
        return $str_xml;
    }
    /**
     * 组装主媒资信息
     * @param unknown $arr_info 主媒资基本信息
     * @param string $arr_info_ex 扩展数据
     * @return string
     */
    private function make_vod_xml($arr_info,$str_Action,$arr_info_ex=null)
    {
        $str_xml ='<Object ElementType="Series" ContentID="'.$arr_info['nns_asset_import_id'].'" Action="'.$str_Action.'" code="'.$arr_info['nns_asset_import_id'].'">';
        $str_xml.=	'<Property Name="Name">'.$arr_info['nns_name'].'</Property>';
        $str_xml.=	'<Property Name="OrderNumber"></Property>';
        $str_xml.=	'<Property Name="OriginalName">'.$arr_info['nns_name'].'</Property>';
        $str_xml.=	'<Property Name="AliasName">'.$arr_info['nns_alias_name'].'</Property>';
        $str_xml.=	'<Property Name="EnglishName">'.$arr_info['nns_eng_name'].'</Property>';
        $str_xml.=	'<Property Name="SortName">'.$arr_info['nns_name'].'</Property>';
        $str_xml.=	'<Property Name="SearchName">'.$arr_info['nns_name'].'</Property>';
        $str_xml.=	'<Property Name="OrgAirDate">'.$arr_info['nns_copyright_date'].'</Property>';
        $str_xml.=	'<Property Name="ReleaseYear">'.$arr_info['nns_show_time'].'</Property>';
        $str_xml.=	'<Property Name="LicensingWindowStart"></Property>';
        $str_xml.=	'<Property Name="LicensingWindowEnd"></Property>';
        $str_xml.=	'<Property Name="CPContentID">'.$arr_info['nns_cp_id'].'</Property>';
        $str_xml.=	'<Property Name="DisplayAsNew"></Property>';
        $str_xml.=	'<Property Name="DisplayAsLastChance"></Property>';
        $str_xml.=	'<Property Name="Macrovision"></Property>';
        $str_xml.=	'<Property Name="Price"></Property>';
        $str_xml.=	'<Property Name="VolumnCount">'.$arr_info['nns_all_index'].'</Property>';
        $str_xml.=	'<Property Name="NewCount">'.$arr_info['nns_new_index'].'</Property>';
        $str_xml.=	'<Property Name="Status">'.$arr_info['nns_state'].'</Property>';
        $str_xml.=	'<Property Name="Description">'.$arr_info['nns_summary'].'</Property>';
        $str_xml.=	'<Property Name="ContentProvider">'.$arr_info['nns_cp_id'].'</Property>';
        $str_xml.=	'<Property Name="KeyWords">'.$arr_info['nns_keyword'].'</Property>';
        $str_xml.=	'<Property Name="OriginalCountry">'.$arr_info['nns_area'].'</Property>';
        $str_xml.=	'<Property Name="ActorDisplay">'.$arr_info['nns_actor'].'</Property>';
        $str_xml.=	'<Property Name="DirectorDisplay">'.$arr_info['nns_director'].'</Property>';
        $str_xml.=	'<Property Name="WriterDisplay">'.$arr_info['nns_screenwriter'].'</Property>';
        $str_xml.=	'<Property Name="Language">'.$arr_info['nns_language'].'</Property>';
        $str_xml.=	'<Property Name="Kind">'.$arr_info['nns_kind'].'</Property>';
        $str_xml.=	'<Property Name="Duration">'.$arr_info['nns_view_len'].'</Property>';
        $str_xml.=	'<Property Name="CategoryName">'.$arr_info['nns_cdn_category_name'].'</Property>';
        $str_xml.=	'<Property Name="CategoryID">'.$arr_info['nns_cdn_category_id'].'</Property>';
        $str_xml.=	'<Property Name="PlayCount">0</Property>';
        $str_xml.=	'<Property Name="CategoryId">0</Property>';
        $str_xml.=	'<Property Name="CategorySort">0</Property>';
        $str_xml.=	'<Property Name="Tags">'.$arr_info['nns_tag'].'</Property>';
        $str_xml.=	'<Property Name="ViewPoint">'.$arr_info['nns_point'].'</Property>';
        $str_xml.=	'<Property Name="StarLevel"></Property>';
        $str_xml.=	'<Property Name="Rating"/>';
        $str_xml.=	'<Property Name="Awards"/>';
        $str_xml.=	'<Property Name="Sort"></Property>';
        $str_xml.=	'<Property Name="Hotdegree"></Property>';
        $str_xml.='</Object>';
        return $str_xml;
    }
    /**
     * 点播主媒资CDN
     * @param
     */
    public function do_video()
    {
        $date = date("Ymd");
        $temp_guid = np_guid_rand();
        if(!isset($this->arr_params['bk_c2_task_info']['nns_ref_id']) || empty($this->arr_params['bk_c2_task_info']['nns_ref_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_video_id字段,参数为:'.var_export($this->arr_params));
        }
        $video_id = $this->arr_params['bk_c2_task_info']['nns_ref_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/depot/depot.class.php';
        //查询主媒资信息
        $result_video = nl_vod::get_video_info_by_id($this->obj_dc, $video_id);
        if($result_video['ret'] !=0)
        {
            return $result_video;
        }
        if(!isset($result_video['data_info'][0]) || !is_array($result_video['data_info'][0]) || empty($result_video['data_info'][0]))
        {
            //主媒资已被删除
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_video;
        }
        $result_video = $result_video['data_info'][0];
        //主媒资扩展信息
        $result_video_ex=array();
        $result_video_ex = nl_vod::query_ex_by_id($this->obj_dc,$result_video['nns_asset_import_id'],$result_video['nns_cp_id']);
        $result_video_ex=array_column($result_video_ex['data_info'], 'nns_value', 'nns_key');
        $result_cp_config = nl_cp::query_by_id($this->obj_dc, $result_video['nns_cp_id']);
        if($result_cp_config['ret'] !=0)
        {
            return $result_cp_config;
        }
        $this->arr_cp_config = (isset($result_cp_config['data_info']['nns_config']) && strlen($result_cp_config['data_info']['nns_config']) >0) ? json_decode($result_cp_config['data_info']['nns_config'],true) : null;
        $result_video_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'video', $video_id,$result_video);
        if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) <1)
        {
            return $result_video_import_info;
        }
        $result_video['nns_cdn_video_guid'] = $result_video_import_info['data_info'];
        $result_depot = nl_depot::get_depot_info($this->obj_dc, null,'video');
        //获取栏目
        if($result_depot['ret'] !=0)
        {
            return $result_depot;
        }
        $result_video['nns_cdn_category_name'] = (isset($result_video['nns_all_index']) && (int)$result_video['nns_all_index'] >1) ? '电视剧' : '电影';
        $result_video['nns_cdn_category_id'] = '';
        if(isset($result_depot['data_info'][0]['nns_category']) && strlen($result_depot['data_info'][0]['nns_category']) >0 && $this->is_xml($result_depot['data_info'][0]['nns_category']))
        {
            $dom = new DOMDocument('1.0', 'utf-8');
            $dom->loadXML($result_depot['data_info'][0]['nns_category']);
            $categorys = $dom->getElementsByTagName('category');
            foreach ($categorys as $category)
            {
                $nns_cdn_category_id = (string)$category->getAttribute('id');
                if($nns_cdn_category_id == $result_video['nns_category_id'])
                {
                    $result_video['nns_cdn_category_id'] = $nns_cdn_category_id;
                    $result_video['nns_cdn_category_name'] = $category->getAttribute('name');
                    break;
                }
            }
        }
        $action = ($this->arr_params['bk_c2_task_info']['nns_action'] !='destroy') ? ($this->arr_params['bk_c2_task_info']['nns_action'] == 'update') ? 'UPDATE' : 'REGIST' : 'DELETE';
        $result_picture = $this->make_image_self($result_video, 'Series',$result_video['nns_asset_import_id'],$action,$date,$temp_guid);
        $xml_str  = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml_str .= '<ADI>';
        $xml_str .= 	'<Objects>';
        $xml_str .=     $this->make_vod_xml($result_video,$action,$result_video_ex);
        if(isset($result_picture['picture']) && strlen($result_picture['picture']) >0)
        {
            $xml_str .= $result_picture['picture'];
        }
	$xml_str .=     '</Objects>';
        if(isset($result_picture['mapping']) && strlen($result_picture['mapping']) >0)
        {
            $xml_str .= 	'<Mappings>';
            $xml_str .= $result_picture['mapping'];
            $xml_str .= 	'</Mappings>';
        }
        $xml_str .= '</ADI>';
        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_video' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type'=>'Series',
            'nns_task_id'=> isset($this->arr_params['bk_c2_task_info']['nns_id'])?$this->arr_params['bk_c2_task_info']['nns_id']:null,
            'nns_task_name'=> isset($this->arr_params['bk_c2_task_info']['nns_name'])?$this->arr_params['bk_c2_task_info']['nns_name']:null,
            'nns_action'=>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => 'Series,'.$action,
            'nns_id'=>$str_guid,
        );
        $result = $this->execute_self_bk_c2($c2_info);
        if($result['ret'] !=0)
        {
            return $result;
        }
        $data_ftp = null;
        $data_ftp[] = array(
            'source_file'=>$result['data_info'],
            'remote_file'=>$temp_guid.'.xml',
        );
        $ftp_url = isset($this->arr_sp_config['ftp_cdn_send_mode_url']) ? $this->arr_sp_config['ftp_cdn_send_mode_url'] : '';
        $result_ftp = $this->push_xml_file($ftp_url,$data_ftp);
        //上传ftp失败 修改日志状态
        if($result_ftp['ret'] !=0)
        {
            $edit_c2_info = array(
                'nns_result'=>"[-1]",
                'nns_notify_result'=>-1,
                'nns_notify_result'=>$result_ftp['reason'],
            );
            nl_c2_log::edit($this->obj_dc, $edit_c2_info,$c2_info['nns_id']);
            //修改任务状态为失败
            nl_c2_task::edit($this->obj_dc, array('nns_status'=>-1), $c2_info['nns_task_id']);
            return $result_ftp;
        }
        //修改任务状态为成功
        nl_c2_task::edit($this->obj_dc, array('nns_status'=>0), $c2_info['nns_task_id']);
        //删除中心同步队列
        $this->del_op_queue($this->arr_params['bk_c2_task_info']['nns_op_id']);
        return $result_ftp;
    }
    /**
     * 点播分集CDN
     * @param
     */
    public function do_index()
    {
        $date = date("Ymd");
        $temp_guid = np_guid_rand();
        if(!isset($this->arr_params['bk_c2_task_info']['nns_ref_id']) || empty($this->arr_params['bk_c2_task_info']['nns_ref_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_index_id字段,参数为:'.var_export($this->arr_params));
        }
        $index_id = $this->arr_params['bk_c2_task_info']['nns_ref_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod_index.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        $result_index = nl_vod_index::get_video_index_info_by_id($this->obj_dc, $index_id);//分集信息
        if($result_index['ret'] !=0)
        {
            return $result_index;
        }
        if(!isset($result_index['data_info'][0]) || !is_array($result_index['data_info'][0]) || empty($result_index['data_info'][0]))
        {
            //分集不存在
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_index;
        }
        $result_index = $result_index['data_info'][0];
        $result_index_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'index', $index_id,$result_index);
        if($result_index_import_info['ret'] !=0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) <1)
        {
            return $result_index_import_info;
        }
        $result_index['nns_cdn_index_guid'] = $result_index_import_info['data_info'];
        //分集扩展信息
        $result_index_ex=array();
        $result_index_ex=nl_vod_index::query_ex_by_id($this->obj_dc,$result_index['nns_import_id'],$result_index['nns_cp_id']);
        $result_index_ex= array_column($result_index_ex['data_info'], 'nns_value', 'nns_key');

        //主媒资信息
        $result_video = nl_vod::get_video_info_by_id($this->obj_dc, $result_index['nns_vod_id']);
        if($result_video['ret'] !=0)
        {
            return $result_video;
        }
        if(!isset($result_video['data_info'][0]) || !is_array($result_video['data_info'][0]) || empty($result_video['data_info'][0]))
        {
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$this->arr_params['bk_c2_task_info']['nns_id']}'", $this->obj_dc->db());
            return $result_video;
        }
        $result_video = $result_video['data_info'][0];
        $result_cp_config = nl_cp::query_by_id($this->obj_dc, $result_video['nns_cp_id']);
        if($result_cp_config['ret'] !=0)
        {
            return $result_cp_config;
        }
        $this->arr_cp_config = (isset($result_cp_config['data_info']['nns_config']) && strlen($result_cp_config['data_info']['nns_config']) >0) ? json_decode($result_cp_config['data_info']['nns_config'],true) : null;
        $result_video_import_info = public_model_exec::get_asset_id_by_sp_id($this->str_sp_id, 'video', $result_index['nns_vod_id'],$result_video);
        if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) <1)
        {
            return $result_video_import_info;
        }
        $result_video['nns_cdn_video_guid'] = $result_video_import_info['data_info'];
        $action = ($this->arr_params['bk_c2_task_info']['nns_action'] !='destroy') ? ($this->arr_params['bk_c2_task_info']['nns_action'] == 'update') ? 'UPDATE' : 'REGIST' : 'DELETE';
        // 	    $action = ($result_index['nns_deleted'] !=1) ? ($result_index['nns_modify_time'] > $result_index['nns_create_time']) ? 'UPDATE' : 'REGIST' : 'DELETE';
        $result_picture = $this->make_image_self($result_index, 'Program', $result_index['nns_import_id'], $action,$date,$temp_guid);
        //$result_index['nns_index'] = (isset($result_index['nns_index']) && $result_index['nns_index'] >=0) ? $result_index['nns_index']+1 : 1;
        $xml_str  = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml_str .= '<ADI>';
        $xml_str .= 	'<Objects>';
        $xml_str .=     $this->make_index_xml($result_index,$action,$result_index_ex);
        if(isset($result_picture['picture']) && strlen($result_picture['picture']) >0)
        {
            $xml_str .= $result_picture['picture'];
        }
        $xml_str .= 	'</Objects>';
        $xml_str .= 	'<Mappings>';
        if(isset($result_picture['mapping']) && strlen($result_picture['mapping']) >0)
        {
            $xml_str .= $result_picture['mapping'];
        }
        $xml_str .=     $this->make_mapping('Series','Program',$result_video['nns_asset_import_id'],$result_index['nns_import_id'],$action,array('Sequence'=>$result_index['nns_index']));
        $xml_str .= 	'</Mappings>';
        $xml_str .= '</ADI>';

        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_index' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type'=>'Program',
            'nns_task_id'=> isset($this->arr_params['bk_c2_task_info']['nns_id'])?$this->arr_params['bk_c2_task_info']['nns_id']:null,
            'nns_task_name'=> isset($this->arr_params['bk_c2_task_info']['nns_name'])?$this->arr_params['bk_c2_task_info']['nns_name']:null,
            'nns_action'=>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => 'Program,'.$action,
            'nns_id'=>$str_guid,
        );
        $result = $this->execute_self_bk_c2($c2_info);
        if($result['ret'] !=0)
        {
            return $result;
        }
        $data_ftp = null;
        $data_ftp[] = array(
            'source_file'=>$result['data_info'],
            'remote_file'=>$temp_guid.'.xml',
        );
        if(isset($result_picture['base_path']) && is_array($result_picture['base_path']) && !empty($result_picture['base_path']))
        {
            foreach ($result_picture['base_path'] as $file_temp_val)
            {
                $data_ftp[] = $file_temp_val;
            }
        }
        $ftp_url = isset($this->arr_sp_config['ftp_cdn_send_mode_url']) ? $this->arr_sp_config['ftp_cdn_send_mode_url'] : '';
        $result_ftp = $this->push_xml_file($ftp_url,$data_ftp);
        //上传ftp失败 修改日志状态
        if($result_ftp['ret'] !=0)
        {
            $edit_c2_info = array(
                'nns_result'=>"[-1]",
                'nns_notify_result'=>-1,
                'nns_notify_result'=>$result_ftp['reason'],
            );
            nl_c2_log::edit($this->obj_dc, $edit_c2_info,$c2_info['nns_id']);
            //修改任务状态为失败
            nl_c2_task::edit($this->obj_dc, array('nns_status'=>-1), $c2_info['nns_task_id']);
            return $result_ftp;
        }
        //修改任务状态为成功
        nl_c2_task::edit($this->obj_dc, array('nns_status'=>0), $c2_info['nns_task_id']);
        //删除中心同步队列
        $this->del_op_queue($this->arr_params['bk_c2_task_info']['nns_op_id']);
        return $result_ftp;
    }
    /**
     * 点播片源CDN
     * @param
     */
    public function do_media()
    {
        if(!isset($this->arr_params['nns_media_id']) || empty($this->arr_params['nns_media_id']))
        {
            return $this->_make_return_data(1,'点播传入参数无nns_media_id字段,参数为:'.var_export($this->arr_params));
        }
        $movie_id = $this->arr_params['nns_media_id'];
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/vod_media/vod_media.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod_index.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_logic/video/vod.class.php';
        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/nn_class/ftp/ftp_push.class.php';
        $result_media = nl_vod_media_v2::query_by_id($this->obj_dc, $movie_id);//片源信息
        if($result_media['ret'] !=0)
        {
            return $result_media;
        }
        if(!isset($result_media['data_info']) || !is_array($result_media['data_info']) || empty($result_media['data_info']))
        {
            //片源不存在
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
            return $result_media;
        }
        $result_media = $result_media['data_info'];
        //片源扩展信息
        $result_media_ex = array();
        $result_media_ex = nl_vod_media_v2::query_ex_by_id($this->obj_dc, $result_media['nns_import_id'],$result_media['nns_cp_id']);
        $result_media_ex = array_column($result_media_ex['data_info'], 'nns_value', 'nns_key');
        if((int)$this->arr_sp_config['disabled_clip'] !== 2 && (int)$this->arr_sp_config['disabled_clip'] !== 3)
        {
            $result_media['nns_url'] = ltrim((trim($this->arr_params['nns_file_path'])),'/');
            if(isset($this->arr_sp_config['media_ftp']) && !empty($this->arr_sp_config['media_ftp']))
            {
                $this->arr_sp_config['media_ftp'] = rtrim((trim($this->arr_sp_config['media_ftp'])),'/');
                if (stripos($result_media['nns_url'], 'http://') === FALSE && stripos($result_media['nns_url'], 'ftp://') === FALSE)
                {
                    $result_media['nns_url'] = $this->arr_sp_config['media_ftp'].'/'.$result_media['nns_url'];
                }
            }
        }
        else
        {
            $result_media['nns_url'] = ltrim((trim($result_media['nns_url'])),'/');
            if(isset($this->arr_sp_config['media_ftp']) && !empty($this->arr_sp_config['media_ftp']))
            {
                $this->arr_sp_config['media_ftp'] = rtrim((trim($this->arr_sp_config['media_ftp'])),'/');
                if (stripos($result_media['nns_url'], 'http://') === FALSE && stripos($result_media['nns_url'], 'ftp://') === FALSE)
                {
                    $result_media['nns_url'] = $this->arr_sp_config['media_ftp'].'/'.$result_media['nns_url'];
                }
            }
        }

        $arr_nns_file_resolution = explode('*', $result_media['nns_file_resolution']);
        $result_media['FrameHeight'] = (isset($arr_nns_file_resolution[0]) && (int)$arr_nns_file_resolution[0] >0) ? $arr_nns_file_resolution[0] : 1080;
        $result_media['FrameWidth'] = (isset($arr_nns_file_resolution[1]) && (int)$arr_nns_file_resolution[1] >0) ? $arr_nns_file_resolution[1] : 1920;
        $result_index = nl_vod_index::get_video_index_info_by_id($this->obj_dc, $result_media['nns_vod_index_id']);
        if($result_index['ret'] !=0)
        {
            return $result_index;
        }
        if(!isset($result_index['data_info'][0]) || !is_array($result_index['data_info'][0]) || empty($result_index['data_info'][0]))
        {
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
            return $result_index;
        }
        $result_index = $result_index['data_info'][0];//分集信息

        $result_video = nl_vod::get_video_info_by_id($this->obj_dc, $result_media['nns_vod_id']);
        if($result_video['ret'] !=0)
        {
            return $result_video;
        }
        if(!isset($result_video['data_info'][0]) || !is_array($result_video['data_info'][0]) || empty($result_video['data_info'][0]))
        {
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
            return $result_video;
        }
        $result_video = $result_video['data_info'][0];

        $result_cp_config = nl_cp::query_by_id($this->obj_dc, $result_video['nns_cp_id']);
        if($result_cp_config['ret'] !=0)
        {
            return $result_cp_config;
        }
        $this->arr_cp_config = (isset($result_cp_config['data_info']['nns_config']) && strlen($result_cp_config['data_info']['nns_config']) >0) ? json_decode($result_cp_config['data_info']['nns_config'],true) : null;

        $date = date("Ymd");
        $temp_guid = np_guid_rand();

        $temp_media_source_url = trim(trim($result_media['nns_url'],'/'),"\\");

        $temp_file_path = pathinfo($temp_media_source_url);
        if(!isset($temp_file_path['extension']) || strlen($temp_file_path['extension']) <1)
        {
            nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_epg_status=100 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
            return $this->_make_return_data(1,'temp set');
        }
        $temp_file_path['extension'] = strtolower($temp_file_path['extension']);
        $result_media['nns_filetype'] = $temp_file_path['extension'];
        // 		if(strtolower($result_media['nns_filetype']) !='ts' || !isset($temp_file_path['extension']) || strtolower($temp_file_path['extension']) !='ts')
        // 		{
        // 		    nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=7,nns_epg_status=100 where nns_id='{$this->arr_params['nns_task_id']}'", $this->obj_dc->db());
        // 		    return $this->_make_return_data(1,'temp set');
        // 		}
        $temp_desc_url = $result_media['nns_cp_id'].'/'.$date .'/' . $temp_guid . '/' . $temp_guid.'.'.$temp_file_path['extension'];
        //$result_media['nns_url'] = $temp_desc_url;
        $action = ($this->arr_params['bk_c2_task_info']['nns_action'] !='destroy') ? ($this->arr_params['bk_c2_task_info']['nns_action'] == 'update') ? 'UPDATE' : 'REGIST' : 'DELETE';
        $xml_str  = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml_str .= '<ADI>';
        $xml_str .= 	'<Objects>';
        $xml_str .=     $this->make_media_xml($result_media,$action,$result_media_ex);
        $xml_str .= 	'</Objects>';
        $xml_str .= 	'<Mappings>';
        $xml_str .=     $this->make_mapping('Program','Movie',$result_index['nns_import_id'],$result_media['nns_import_id'],$action);
        $xml_str .=     $this->make_mapping('Series','Program',$result_video['nns_asset_import_id'],$result_index['nns_import_id'],$action);
        $xml_str .= 	'</Mappings>';
        $xml_str .= '</ADI>';

        $str_guid = np_guid_rand();
        $file_name = $this->str_sp_id . '_' . date('His') . '_' . $str_guid . '_' . 'vod_media' . '_' . $action . '.xml';
        $c2_info = array(
            'nns_task_type'=>'Movie',
            'nns_task_id'=> isset($this->arr_params['nns_task_id'])?$this->arr_params['nns_task_id']:null,
            'nns_task_name'=> isset($this->arr_params['nns_task_name'])?$this->arr_params['nns_task_name']:null,
            'nns_action'=>	$action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => 'Movie,'.$action,
            'nns_id'=>$str_guid,
        );
        $result = $this->execute_self_bk_c2($c2_info);
        if($result['ret'] !=0)
        {
            return $result;
        }
        $data_ftp = null;
        $data_ftp[] = array(
            'source_file'=>$result['data_info'],
            'remote_file'=>$temp_guid.'.xml',
        );
        $ftp_url = isset($this->arr_sp_config['ftp_cdn_send_mode_url']) ? $this->arr_sp_config['ftp_cdn_send_mode_url'] : '';
        $result_ftp = $this->push_xml_file($ftp_url,$data_ftp);
        if($result_ftp['ret'] !=0)
        {
            $edit_c2_info = array(
                'nns_result'=>"[-1]",
                'nns_notify_result'=>-1,
                'nns_notify_result'=>$result_ftp['reason'],
            );
            nl_c2_log::edit($this->obj_dc, $edit_c2_info,$c2_info['nns_id']);
            //修改任务状态为失败
            nl_c2_task::edit($this->obj_dc, array('nns_status'=>-1), $c2_info['nns_task_id']);
            return $result_ftp;
        }
        //修改任务状态为成功
        nl_c2_task::edit($this->obj_dc, array('nns_status'=>0), $c2_info['nns_task_id']);
        //删除中心同步队列
        $this->del_op_queue($this->arr_params['bk_c2_task_info']['nns_op_id']);
        
        return $result_ftp;
    }
    /**
     * 中国电信标准C2
     * @param unknown $c2_info
     */
    public function execute_self_bk_c2($c2_info)
    {
        $c2_info['nns_type'] = 'std';
        $c2_info['nns_org_id'] = $this->str_sp_id;

        $sub_path = date('Y-m-d');
        $file = $c2_info['nns_url'];
        $c2_info['nns_url'] = $sub_path . '/' . $file;
        //生成soap xml文件 路径
        $file_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/mgtv/' . $this->str_sp_id . '/inject_xml/' . $sub_path . '/';
        if (!is_dir($file_path))
        {
            mkdir($file_path, 0777, true);
        }
        $file_path .= $file;
        $result = @file_put_contents($file_path, $c2_info['nns_content']);
        $CmdFileURL = trim(rtrim($this->arr_sp_config['xml_ftp'],'/')) . '/' . trim(ltrim($c2_info['nns_url'],'/'));

        $result = $result ? 0 : -1;
        $c2_info['nns_result'] = "[{$result}]";
        $c2_info['nns_notify_result'] = $result;
        nl_c2_log::add($this->obj_dc, $c2_info);
        return ($result== 0) ? $this->_make_return_data(0,'ok',$file_path) :  $this->_make_return_data(1,'error',$file_path);
    }
    /**
     *推送文件信息给下游
     */
    private function push_xml_file($ftp_url,$arr_file)
    {
        $ftp_url = trim($ftp_url,'/');
        if(strlen($ftp_url) <1)
        {
            return $this->_make_return_data(1,'sp c2_import_push_dst_url not set');
        }
        $arr_ftp_config = parse_url($ftp_url);
        $host_ftp = (isset($arr_ftp_config["host"]) && strlen($arr_ftp_config["host"]) > 0) ? $arr_ftp_config["host"] : '';
        $user_ftp = (isset($arr_ftp_config["user"]) && strlen($arr_ftp_config["user"]) > 0) ? $arr_ftp_config["user"] : '';
        $pass_ftp = (isset($arr_ftp_config["pass"]) && strlen($arr_ftp_config["pass"]) > 0) ? $arr_ftp_config["pass"] : '';
        $path_ftp = (isset($arr_ftp_config["path"]) && strlen($arr_ftp_config["path"]) > 0) ? $arr_ftp_config["path"] : '';
        $port_ftp = (isset($arr_ftp_config["port"]) && strlen($arr_ftp_config["port"]) > 0) ? $arr_ftp_config["port"] : 21;

        $path_ftp = trim(trim($path_ftp,'/'));
        $path_ftp = (strlen($path_ftp) >0) ? '/'.$path_ftp : '/';
        foreach ($arr_file as $file_val)
        {
            $obj_ftp = new nl_ftp($host_ftp, $user_ftp, $pass_ftp,$port_ftp,30);
            $result_upload = $obj_ftp->upload_file($path_ftp.'/'.$file_val['remote_file'],$file_val['source_file']);
            $obj_ftp->my_destruct();
            unset($obj_ftp);
            if($result_upload['ret'] !=0)
            {
                for ($i=0;$i<2;$i++)
                {
                    $obj_ftp = new nl_ftp($host_ftp, $user_ftp, $pass_ftp,$port_ftp,30);
                    $result_upload = $obj_ftp->upload_file($path_ftp.'/'.$file_val['remote_file'],$file_val['source_file']);
                    $obj_ftp->my_destruct();
                    unset($obj_ftp);
                    if($result_upload['ret'] == '0')
                    {
                        break;
                    }
                }
                if($result_upload['ret'] !='0')
                {
                    return $result_upload;
                }
            }
        }
        return $this->_make_return_data(0,'ftp upload ok');
    }
    /**
     * 组装反馈数据
     * @param number $ret
     * @param string $reason
     * @param string $reason_en
     * @param string $data
     * @return multitype:number string
     */
    public function _make_return_data($ret=1,$reason='error',$data=null)
    {
        return array(
            'ret'=>$ret,
            'reason'=>$reason,
            'data_info'=>$data,
        );
    }

    /**
     * 组装img
     * @param unknown $arr_video
     * @param unknown $type
     */
    private function make_image_self($arr_video,$parent_type,$parent_id,$action,$date,$temp_guid)
    {
        $str_base_img_url = isset($this->arr_cp_config['g_ftp_conf']['down_img_dir']) ? trim($this->arr_cp_config['g_ftp_conf']['down_img_dir']) : '';
        $str_base_img_url = rtrim(rtrim($str_base_img_url,'/'),'\\');
        $str_picture_obj = $str_picture_mapping = '';
        switch ($parent_type)
        {
            case 'Series':
                $arr_map = array(
                    'nns_image0'=>1,
                    'nns_image1'=>2,
                    'nns_image2'=>3,
                    'nns_image_v'=>4,
                    'nns_image_s'=>6,
                    'nns_image_h'=>5,
                );
                break;
            case 'Program':
                $arr_map = $this->arr_vod_index_img;
                break;
        }
        if(!is_array($arr_map) || empty($arr_map))
        {
            return null;
        }
        foreach ($arr_map as $key=>$val)
        {
            if(isset($arr_video[$key]) && strlen($arr_video[$key]) >0)
            {
                $arr_video[$key] = ltrim(ltrim(trim($arr_video[$key]),'/'),'\\');
                $id = md5($key.$arr_video[$key]);
                $picture = array(
                    'FileURL'=>empty($str_base_img_url) ? $arr_video[$key]: $str_base_img_url.'/'.$arr_video[$key],
                    'Type'=>$val,
                    'Description'=>'',
                );
                $str_picture_obj .= $this->make_object('Picture', $id,$action,$picture);
                $str_picture_mapping .= $this->make_mapping($parent_type,'Picture',$parent_id, $id, $action,array('Type' => $val),$val);
             }
        }
        return array(
            'picture'=>$str_picture_obj,
            'mapping'=>$str_picture_mapping,
        );
    }
    /**
     * 删除中心同步队列
     * @param unknown $nns_op_id
     *
     */
    private function del_op_queue($nns_op_id)
    {
      $db = nn_get_db(NL_DB_WRITE);
      $sql="delete from nns_mgtvbk_op_queue where nns_id='$nns_op_id'";
      $re=nl_execute_by_db($sql,$db);
      return $re;
    }
}
